<template>
	<comRoot>
		<template #page>
			<image v-if="commonConfigs && commonConfigs.domainFrontFileLink" :src="`${commonConfigs.domainFrontFileLink}/files/images/page-bg.png`" class="bg" />
			
			<comDetailNavigateBack title="商品详情页" />
			
			<view class="shop-info-page relative">
				<scroll-view scroll-y="true" :style="{ height: 'calc(100vh - ' + commonNavHeight + ' - 208rpx)' }">
					
					<view class="" :style="{
							'background-image': `url(${commonConfigs.domainFrontFileLink}/files/images/shopinfo/award-info-bg.png)`
						}"
						style="width: 686rpx;height: 858rpx;background-size: 100% 100%;margin: auto;"
						>
						<view class="relative award-info-box flex-all-center margin-auto">
							<!-- <image v-if="commonConfigs && commonConfigs.domainFrontFileLink" 
								:src="`${commonConfigs.domainFrontFileLink}/files/images/shopinfo/award-info-bg.png`" 
								class="bg" style="width: 686rpx;height: 848rpx;" /> -->
							<!-- widthFix -->
							<image :src="productInfoData.product_detail_image" mode=""
								style="width: 646rpx;height: 646rpx;border-radius: 16rpx;"
							></image>
						</view>
						
						<view class="shopinfo-content">
							
							<view class="shopinfo-nums">							
								<text v-if="[3].includes(productInfoData.product_buy_type)">{{ productInfoData.product_price }}</text>
								<text class="price-unit" v-if="[3].includes(productInfoData.product_buy_type)">元</text>
								
								<text v-if="[5, 1].includes(productInfoData.product_buy_type)">{{ productInfoData.balance }}</text>
								<text class="price-unit" v-if="[5, 1].includes(productInfoData.product_buy_type)">机能</text>
								
								<text style="margin: 0 10rpx;" v-if="[3, 5].includes(productInfoData.product_buy_type)"> + </text>
								
								<text v-if="[3, 5, 2].includes(productInfoData.product_buy_type)">{{ productInfoData.points }}</text>
								<text class="price-unit" v-if="[3, 5, 2].includes(productInfoData.product_buy_type)">积分</text>
							</view>
							
							<view class="shopinfo-title truncate">
								{{ productInfoData.product_name }}
							</view>
						
							<view class="shopinfo-desc flex">
								<view class="flex-align-items-center" style="margin-right: 80rpx;">
									<image style="width: 23rpx;height: 23rpx;margin-right: 15rpx;" v-if="commonConfigs && commonConfigs.domainFrontFileLink" :src="`${commonConfigs.domainFrontFileLink}/files/images/shopinfo/icon1.png`" mode=""></image>
									<text>百分百正品</text>
								</view>
								<view class="flex-align-items-center">
									<image style="width: 23rpx;height: 23rpx;margin-right: 15rpx;" v-if="commonConfigs && commonConfigs.domainFrontFileLink" :src="`${commonConfigs.domainFrontFileLink}/files/images/shopinfo/icon2.png`" mode=""></image>
									<text>72小时内发货</text>
								</view>
							</view>
						</view>
					</view>
					
				</scroll-view>

				<view :class="['shopinfo-bottom relative fixed', 'flex-justify-content-between']">
					<image v-if="commonConfigs && commonConfigs.domainFrontFileLink" :src="`${commonConfigs.domainFrontFileLink}/files/images/shopinfo/detail-footer-bg.png`" class="bg" />
					
					<view class="bottom-view-left flex relative flex-direction-column flex-start">
						<view class="flex relative" style="margin-left: 33rpx;"
							@click="gooDetailUrlFun('/secondary/userBillListPage/userBillListPage?type=balance')"
							v-if="[5, 1].includes(productInfoData.product_buy_type)">
							<image class="view-left-icon" style="width: 40rpx;height: 40rpx;"
								v-if="commonConfigs && commonConfigs.domainFrontFileLink"
								:src="`${commonConfigs.domainFrontFileLink}/files/images/user/branch-icon.png`"
								mode=""></image>
								 <!-- v-show="token" -->
							<text class="font-hanserif-bold settlement_text"
								>{{ '旺卡能：' + userInfo.balance || '0' }}
							</text>
						</view>
						
						<view style="margin: 6rpx 0;" class="" v-if="[5, 3].includes(productInfoData.product_buy_type)"></view>
						
						<view class="flex relative" style="margin-left: 33rpx;"
							@click="gooDetailUrlFun('/secondary/userBillListPage/userBillListPage?type=integral')"
							v-if="[3, 5, 2].includes(productInfoData.product_buy_type)">
							<image class="view-left-icon"
								v-if="commonConfigs && commonConfigs.domainFrontFileLink"
								:src="`${commonConfigs.domainFrontFileLink}/files/images/user/point-icon.png`"
								mode=""
								style="width: 40rpx;height: 40rpx;"></image>
							<text class="font-hanserif-bold settlement_text"
								>{{ '旺卡币：' + userInfo.points || '0' }}
							</text>
						</view>
					</view>
					
					<view class="footer-btn relative"
						style="margin-right: 30rpx;width: 243rpx;height: 80rpx;"
						@click="setPopupFun">
						<image src="/static/images/public_imgs/popup-sure-btn-bg.png" class="bg" mode=""></image>
						<text class="flex flex-all-center relative"
						style="width: 243rpx;height: 80rpx;font-size: 36rpx;font-weight: 800;color: #FFFFFF;"
						>购买</text>
					</view>
				</view>

				<comPopup v-model="showGoodPopup" title="购买商品" popupOfMaxHeight="852rpx">

					<view class="order-view">
						<view class="order-view-box relative flex flex-align-items-center">
							<image
								v-if="commonConfigs && commonConfigs.domainFrontFileLink"
								:src="`${commonConfigs.domainFrontFileLink}/files/images/common/box-list-item-bg.png`"
								class="bg" mode=""></image>
							
							<view class="item-cover-box flex-all-center relative">
								<image class="bg"
									:src="commonConfigs.domainFrontFileLink + '/files/images/welfareHouse/goods-bg.png'"
									mode=""></image>
								<image :src="productInfos.product_cover" class="item-cover" mode="aspectFill"></image>
							</view>
							
							<view class="view-box-info relative truncate flex-full">
								<view class="view-box-name truncate font-hanserif-bold"> {{ productInfos.product_name }}</view>
								
								<view class="view-box-nums"> 
									<text>价值：</text>
									
									<text v-if="[1, 5].includes(productInfos.product_buy_type)">{{ productInfos.balance }}</text>
									<text v-if="[1, 5].includes(productInfos.product_buy_type)">机能</text>
								
									<text v-if="[3].includes(productInfos.product_buy_type)">{{ productInfos.product_price }}</text>
									<text v-if="[3].includes(productInfos.product_buy_type)">元</text>
									
									<text style="margin: 0 10rpx;" v-if="[3, 5].includes(productInfos.product_buy_type)"> + </text>
									
									<text v-if="[2, 3, 5].includes(productInfos.product_buy_type)">{{ productInfos.points }}</text>
									<text v-if="[2, 3, 5].includes(productInfos.product_buy_type)">积分</text>
								</view>
								
								<view class="order-num flex flex-justify-content-between">
									<view class="num"> 数量：{{ productInfos.product_num }} </view>
									
									<view class="flex text-center input-bottom">
										<view class="oper-btn-num relative" @click="setNumsFun('reduces')">
											<image class="bg"
												src="/static/images/public_imgs/reduce-icon-img.png"
												mode=""></image>
										</view>
										
										<input v-model="productInfos.product_num" type="number" value="" class="input-num" @blur="inputBlur" />
										
										<view class="oper-btn-num relative" @click="setNumsFun('adds')">
											<image class="bg"
												src="/static/images/public_imgs/add-icon-img.png"
												mode=""></image>
										</view>
									</view>
								</view>
							</view>
						</view>
						
						<view class="bag-pay-info">
							<comPayType v-if="productInfoData.product_buy_type == 3 && showGoodPopup" v-model="currentPayType"></comPayType>
						</view>
					</view>
					<template #footer>
						<view class="page-bottom flex flex-justify-content-between">
							<view class="page-nums">
								<view class="num-box" style="font-size: 38rpx;color: #FF8B1D;" v-if="[1].includes(productInfos.product_buy_type)">
									<text style="font-size: 26rpx;color: #111111;">总计：</text>
									<text>{{ productInfos.allPrice }}</text>
									<text style="font-size: 26rpx;" v-if="productInfos.product_buy_type == 1">机能</text> 
								</view>
								
								<view class="num-box" style="font-size: 38rpx;color: #FF8B1D;" v-if="[2].includes(productInfos.product_buy_type)">
									<text style="font-size: 26rpx;color: #111111;">总计：</text>
									<text>{{ productInfos.allPoints }}</text>
									<text style="font-size: 22rpx;" v-if="productInfos.product_buy_type == 2">积分</text>
								</view>
								
								<view class="num-box" style="font-size: 38rpx;color: #FF8B1D;" v-if="[3, 5].includes(productInfos.product_buy_type)">
									<view style="font-size: 28rpx;color: #111111;">总计：</view>
									<text>{{ productInfos.allPrice }}</text>
									<text style="font-size: 22rpx;" v-if="productInfos.product_buy_type == 3">元</text>
									<text style="font-size: 26rpx;" v-if="productInfos.product_buy_type == 5">机能</text>
									<text style="font-size: 26rpx;" >&nbsp;&nbsp; &nbsp;&nbsp; + &nbsp;&nbsp;
										<text style="font-size: 38rpx;">{{productInfos.allPoints}}</text>
										<text>积分</text>
									</text>
								</view>
							</view>
							
							<view class="bottom-pay-btn" style="width: 243rpx;height: 80rpx;">
								<comSubmitBtn @click="payOrderFun">立即支付</comSubmitBtn>
							</view>
						</view>
					</template>
				</comPopup>

				<view class="page-side-btns flex flex-direction-column">
					<view class="page-side-btn-bg">
						<image v-if="commonConfigs && commonConfigs.domainFrontFileLink" :src="`${commonConfigs.domainFrontFileLink}/files/images/common/ico-bag.png`" @click="gooDetailUrlFun('/secondary/bagPage/bagPage?bagOperType=shop')" mode=""></image>
					</view>
				</view>
			</view>
		</template>
	</comRoot>
</template>

<script>
	import store from '@/store';
	import { ACTIONS } from '@/store/modules/userStore';
	
	import { payment } from '@/setupproject/PAYS_FUN';
	import otherpay from '@/inmixed/otherpay.mixin.js'
	import { wxAuthSetFun, addPhoneSetFun, setAsyncFunWait } from '@/setupproject/TOOLS_FUN';
	import { getProductInfoApi, getProductOrderApi, getProductOrderPreApi, getUserBalanceOrderConfirmApi } from '@/setupproject/INTERFACE.js';
	
	export default {
		name: 'shopInfoPage',
		mixins: [otherpay],
		data() {
			return {
				showGoodPopup: false,
				apiPayTypeVal: 0,
				productIds: '',
				currentPayType: 'wxpay',
				payBeInfos: {
					isPayBackSence: false,
					type: null,
					order_num: null,
					payBeScene: ''
				},
				productInfoData: {},
				submitLoading: false,
				productInfos: {
					product_num: 1
				},
			};
		},
		onLoad({ id }) {
			this.productIds = id;
			
			if (this.token) {
				this.$store.dispatch('USER_INFO_GET_FUN');
			}
			
			this.getProductInfoApi();
		},
		onShow() {
			// #ifdef APP-PLUS
			if(this.$store.getters.detailRechargeFlag) {
				uni.$emit('update', 'comRewardOrder');
				
				// 详情页充值标志位
				this.$store.commit('SET_DETAIL_RECHARGE_FLAG', false);
				return;
			}
			// #endif
			
			// 监听返回当前平台时触发支付结果事件
			if(this.payBeInfos.isPayBackSence && ['adapay_mini', 'alipay', 'yeepay_wx', 'adapay_alipay', 'mbpay_jump_mini'].includes(this.currentPayType)){
				this.payBeInfos.isPayBackSence = !this.payBeInfos.isPayBackSence;
				this.$store.commit('SET_WATCH_PLAT_PARAMS', {
					'type': this.payBeInfos.type,
					'balance_order_num': this.payBeInfos.balance_order_num,
					'msg': '已购买成功，请去赏袋查看',
					'isReward': true
				});
			}
		},

		watch: {
			// 监听支付结果
			async orderPayStatusPopup(pay_status) {
				if (pay_status) {
					await store.dispatch(ACTIONS.USER_INFO_GET_FUN);
					this.showGoodPopup = false;
				}
			},
			showGoodPopup(v) {
				if (v) {
					// this.getProductOrderPreApi();
				} else {
					this.submitLoading = false
					this.productInfos.product_num = 1;
					this.$forceUpdate();
				}
			},
			
		},
		computed: {
			token() {
				return this.$store.getters.token;
			},
			// 支付订单结果
			orderPayStatusPopup() {
				return this.$store.getters.orderPayStatusPopup || {};
			},
			commonNavHeight() {
				return store.getters.commonNavHeight + 'px';
			},
			userInfo() {
				return this.$store.getters.userInfo;
			},
			allPrice() {
				if (this.productInfoData) {
					let allPrice = 0; // 总计
					
					// 商品价格 支付
					if([3].includes(this.productInfos.product_buy_type)) {
						allPrice = this.productInfos.product_num * Number(this.productInfos.product_price); 
					}
					
					// 商品价格 机能
					if([1, 5].includes(this.productInfos.product_buy_type)) {
						allPrice = this.productInfos.product_num * Number(this.productInfos.balance); 
					}
					
					// 积分
					let allPoints = this.productInfos.product_num * this.productInfos.points; 
					
					this.$set(this.productInfos, 'allPoints', allPoints);
					this.$set(this.productInfos, 'allPrice', allPrice);
					
					return allPrice;
				} else {
					return '-';
				}
			},
			commonConfigs() {
				return this.$store.getters.commonConfigs || {};
			},
			
		},
		methods: {
			async setPopupFun() {
				// #ifdef MP-WEIXIN
				// 支付前验证是否已登录
				if (!wxAuthSetFun()) return;
				// #endif
			
				// #ifdef APP-PLUS
				// 支付前验证是否已登录
				if (await store.dispatch('SHOW_LOGIN_APP_GET_FUN')) return;
				// 支付前验证是否已绑定手机
				if (addPhoneSetFun()) return;
				// #endif
				
				const { product_cover, product_price, product_buy_type, product_name, points, balance } = this.productInfoData;
				this.productInfos = {
					points,
					balance,
					product_name,
					product_price,
					allPoints: this.allPoints,
					allPrice: this.allPrice,
					product_num: 1,
					product_buy_type,
					product_cover,
				};
				
				this.submitLoading = false;
				this.getProductOrderPreApi();
			},
			
			// 获取pay-type组件的选择值
			setCurrentPaysFun(value) {
				this.currentPayType = value;
			},
			
			// type: adds增加  reduces 减少
			setNumsFun(type) {
				// 减少
				if (type === 'reduces') {
					if (this.productInfos.product_num <= 1) {
						return uni.showToast({
							title: '数量不能少于1个',
							icon: 'none'
						});
					}
					this.productInfos.product_num--;
					this.$forceUpdate();
				}
				// 新增
				if (type === 'adds') {
					if (this.productInfos.product_num >= this.productInfos.product_max_num) {
						return uni.showToast({
							title: '数量已是最大',
							icon: 'none'
						});
					}
					this.productInfos.product_num++;
					this.$forceUpdate();
				}
				
				this.accountPriceFun();
			},
			
			// 获取商品详情
			async getProductInfoApi() {
				const { data, msg, code } = await getProductInfoApi({ product_id: this.productIds });

				if (code !== 200) {
					return uni.showToast({
						title: msg,
						icon: 'none'
					});
				}
				this.productInfoData = data;
			},
			
			async inputBlur() {
				this.productInfos.product_num = parseInt(this.productInfos.product_num);
			
				if (!this.productInfos.product_num) {
					await setAsyncFunWait(200);
					this.productInfos.product_num = 1;
					await setAsyncFunWait(200);
			
					uni.showToast({
						title: `数量不少于1`,
						icon: 'none'
					});
				}
				
				if (this.productInfos.product_num > this.productInfos.product_max_num) {
					await setAsyncFunWait(200);
					this.productInfos.product_num = this.productInfos.product_max_num;
					await setAsyncFunWait(200);
			
					uni.showToast({
						title: `数量已超出范围`,
						icon: 'none'
					});
				}
				
				this.accountPriceFun();
			},
			
			accountPriceFun() {
				let allPrice = 0; //商品价格
				
				// 3支付+积分
				if([3].includes(this.productInfos.product_buy_type)) {
					allPrice = this.productInfos.product_num * Number(this.productInfos.product_price);
				}
				
				// 1机能 , 5机能 + 积分
				if([1, 5].includes(this.productInfos.product_buy_type)) {
					allPrice = this.productInfos.product_num * Number(this.productInfos.balance);
				}
				
				let allPoints = this.productInfos.product_num * this.productInfos.points;
				
				this.$set(this.productInfos, 'allPoints', allPoints);
				this.$set(this.productInfos, 'allPrice', allPrice);
			},
			
			async gooDetailUrlFun(url) {
				// #ifdef APP-PLUS
				// 支付前验证是否已登录
				if (await store.dispatch('SHOW_LOGIN_APP_GET_FUN')) return;
				// #endif
				uni.navigateTo({
					url: url
				});
			},

			// 订单接口参数
			orderInfoDats() {
				if (!this.productInfos) {
					return {};
				}
				return {
					product_id: this.productIds,
					product_num: this.productInfos && this.productInfos.product_num ? this.productInfos.product_num : 1,
					pay_channel: this.currentPayType,
				};
			},
			
			// 确认购买 下单
			async payOrderFun() {
				if (this.submitLoading) return;

				let payType = this.currentPayType || 'wxpay';
				this.submitLoading = true;
				
				let orderParame = {
					pay_channel: payType,
					product_id: this.productIds,
					product_num: this.productInfos.product_num,
				}
				
				const { code, data, msg } = await getProductOrderApi(orderParame);
			
				if (code !== 200) {
					this.submitLoading = false;
					return uni.showToast({
						title: msg,
						icon: 'none'
					});
				}
				
				if (!data.is_need_wx_pay) {
					uni.showToast({
						title: msg,
						icon: 'none'
					});
					await this.$store.dispatch('USER_INFO_GET_FUN');
					this.showGoodPopup = false;
					this.submitLoading = false;
					return;
				}
				
				// 原生支付： 微信、小程序、支付宝
				if (['wxpay', 'alipay_method', 'wxapp', 'mbpay_wxmini'].includes(payType)) {
					try {
						await payment(data, this.currentPayType || 'wxpay', this.apiPayTypeVal);
						const { code } = await getUserBalanceOrderConfirmApi({
							type: 5,
							balance_order_num: data.order_num
						});
						this.submitLoading = false;
						this.showGoodPopup = false;
						if(code === 200){
							uni.showToast({
								title: '已购买成功！',
								icon: 'success'
							});
						}
						await setAsyncFunWait(2000);
						store.dispatch(ACTIONS.USER_INFO_GET_FUN);
					} catch (err) {
						this.submitLoading = false;
						console.error(err);
					}
					return;
				}
				
				// 第三方小程序微信
				if (['adapay_mini', 'yeepay_wx', 'adapay_alipay', 'lianlianpay', 'mbpay_jump_mini'].includes(payType)) {
					try {
						data.balance_order_num = data.order_num;
						return this.launchMPToPayFun(data, payType);
					} catch (e) {
						this.submitLoading = false;
						console.error(e);
					}
					return;
				}
			},
			
			// 商品生成预订单号
			async getProductOrderPreApi() {
				if (!this.productIds) return;
				const { data } = await getProductOrderPreApi(this.orderInfoDats());
				if (!data) return;
				
				this.$set(this.productInfos, 'allPrice', data.product_info && data.product_info.reward_price_final);
				this.$set(this.productInfos, 'allPoints', data.product_info && data.product_info.reward_price_final);
				this.$set(this.productInfos, 'price', data.product_info && data.product_info.reward_price);
				this.$set(this.productInfos, 'is_show_reward_price_1', data.is_show_reward_price_1 || 0);
				this.$set(this.productInfos, 'max_can_buy', data.product_info && data.product_info.max_can_buy);
				this.$set(this.productInfos, 'show_recovery', data.show_recovery);
				this.$set(this.productInfos, 'is_view_pay_agreement', data.is_view_pay_agreement)
			
				this.accountPriceFun();
				this.showGoodPopup = true;
			},
			
		}
	};
</script>

<style lang="scss" scoped>
	.shop-info-page {
		font-size: 28rpx;
		color: #111111;
		
		.award-info-box {
			width: 692rpx;
			height: 692rpx;
			overflow: hidden;
			margin-top: 30rpx;
		}
		
		.shopinfo-content {
			padding: 0 30rpx;
			font-weight: bold;
			.shopinfo-nums {
				font-size: 40rpx;
				color: #79F6FF;
				line-height: 38rpx;
				// margin: 40rpx 0;
				.price-unit {
					font-size: 28rpx;
					margin-left: 10rpx;
				}
			}
			.shopinfo-title {
				color: #FFFFFF;
				margin-top: 16rpx;
				margin-bottom: 18rpx;
				font-size: 36rpx;
				line-height: 38rpx;
			}
			.shopinfo-desc {
				color: #FFFFFF;
				font-size: 20rpx;
				// margin: 40rpx 0;
				font-weight: 100;
			}
		}
		
		.shopinfo-bottom {
			width: 100vw;
			height: 172rpx;
			align-items: center;
			bottom: 0;
			
			.bottom-view-left {
				// margin-left: 33rpx;
				font-size: 28rpx;
				.view-left-icon {
					width: 37rpx;
					height: 38rpx;
					margin-right: 10rpx;
				}
			}
		}
		
		.item-cover-box {
			width: 138rpx;
			height: 138rpx;
			overflow: hidden;
			margin-right: 30rpx;
		}
		
		.item-cover {
			width: 96rpx;
			height: 96rpx;
		}

		.order-view-box {
			padding: 0 38rpx;
			margin: 0 22rpx;
			height: 220rpx;
			.order-cover {
				height: 150rpx;
				margin-right: 32rpx;
				.cover {
					width: 110rpx;
					height: 150rpx;
					border-radius: 10rpx;
				}
			}
			.view-box-info {
				.view-box-name {
					font-size: 30rpx;
					margin-bottom: 16rpx;
				}
				.input-bottom {
					right: 20rpx;
					bottom: 20rpx;
					line-height: 35rpx;
					background: #80B3F1;
					border-radius: 18rpx;
					
					.oper-btn-num {
						width: 36rpx;
						height: 36rpx;
					}
				
					.input-num {
						width: 3em;
						height: 35rpx;
						min-height: 35rpx;
						line-height: 1;
					}
				}
			}
		}
		
		.bag-pay-info {
			margin-top: 12rpx;
		}
		
		.page-bottom {
			.page-nums {
				font-size: 30rpx;
				color: #111111;
				.num-box {
					font-size: 40rpx;
					font-weight: 800;
					color: #FF8B1D;
				}
			}
		}
		// 侧边按钮
		.page-side-btns {
			position: fixed;
			right: 17rpx;
			bottom: 400rpx;
			.page-side-btn-bg {
				width: 114rpx;
				height: 126rpx;
				> image {
					width: 100%;
					height: 100%;
				}
			}
		}
		
		.settlement_text {
			font-size: 24rpx;
			color: #FFFFFF;
		}
	}
</style>
